/**
 * Created with IntelliJ IDEA.
 * User: ajhin
 * Date: 7/12/14
 * Time: 8:36 AM
 * To change this template use File | Settings | File Templates.
 */
package com.societyGames2.convert
{
import org.as3commons.asblocks.parser.antlr.LinkedListToken;
import org.as3commons.asblocks.parser.antlr.LinkedListTree;
import org.as3commons.asblocks.parser.antlr.as3.AS3Parser;
import org.as3commons.asblocks.parser.antlr.as3.AS3Parser;

public class ConvertToTreeText
{
  private var _tabCount:int = 0;

  public function convertParseTreeToTreeText(tree:LinkedListTree):String
  {
    if (tree.children == null || tree.children.length == 0)
    {
      return convertLeafToTreeText(tree);
    }

    var treeText:String = createTabs();
    if (!tree.isNil)
    {
      treeText += AS3Parser.tokenNames[tree.type] + "\n";
      _tabCount++;
    }
    for (var i:int = 0; tree.children != null && i < tree.children.length; i++)
    {
      var t:LinkedListTree = LinkedListTree(tree.getChild(i));
      treeText += convertParseTreeToTreeText(t);
    }
    if (!tree.isNil)
    {
      _tabCount--;
    }
    return treeText;
  }

  private function createTabs():String
  {
    var text:String = "";
    for (var index:int = 0; index < _tabCount; index++)
    {
      text += "+";
    }
    return text;
  }

  private function convertLeafToTreeText(tree:LinkedListTree):String
  {
    var treeText:String = createTabs() + AS3Parser.tokenNames[tree.type] + ": ";
    var currentToken:LinkedListToken = tree.getStartToken();
    var stopToken:LinkedListToken = tree.getStopToken();
    while (currentToken != null)
    {
      treeText += currentToken.text;
      if (currentToken == stopToken)
      {
        break;
      }
      currentToken = currentToken.getNext();
    }
    treeText += "\n";
    return treeText;
  }
}
}
